local WnUtil = require("utils/wnutil")

local function DeltaModifier(inst, amount, overtime, cause, ignore_invincible, afflicter, ignore_absorb)
    if inst.components.health:GetPercent() > 0.5  then
        amount = amount * 0.5
    end
    return amount
end

local function OnHealthDelta(inst, data)
    if not data or data.newpercent == nil then
        return
    end

    if data.newpercent < 0.5 then
        inst.components.locomotor:SetExternalSpeedMultiplier(inst, "health_percent", 1.5)
    else
        inst.components.locomotor:RemoveExternalSpeedMultiplier(inst, "health_percent")
    end
end

local function Find_Witch_Gisela_Mini(inst)
    local witch_gisela_mini = TheSim:FindFirstEntityWithTag("witch_gisela_mini")
    if witch_gisela_mini then
        inst.components.locomotor:SetExternalSpeedMultiplier(inst, "witch_gisela_mini", 1.5)
    else
        inst.components.locomotor:RemoveExternalSpeedMultiplier(inst, "witch_gisela_mini")
    end
end

local function fn()
    local inst = Prefabs["eyeofterror"].fn()

    if not TheWorld.ismastersim then
        return inst
    end

    inst.components.health:SetMaxHealth(TUNING.WITCH_GISELA_HEALTH)
    inst.components.health.deltamodifierfn = DeltaModifier

    inst.components.combat:SetDefaultDamage(TUNING.WITCH_GISELA_DAMAGE)
    inst.components.combat.playerdamagepercent = TUNING.WITCH_GISELA_DAMAGEPLAYERPERCENT

    inst:ListenForEvent("healthdelta", OnHealthDelta)

    local _spawnminieyes_timeline3_fn = inst.sg.sg.states["spawnminieyes"].timeline[3].fn
    inst.sg.sg.states["spawnminieyes"].timeline[3].fn = function(inst)
        return WnUtil.HookSpawnPrefab("eyeofterror_mini_grounded", "witch_gisela_mini_grounded", _spawnminieyes_timeline3_fn, inst)
    end

    local _onenter = inst.sg.sg.states["spawnminieyes_mouth_loop"].onenter
    inst.sg.sg.states["spawnminieyes_mouth_loop"].onenter = function(inst)
        return WnUtil.HookSpawnPrefab("eyeofterror_mini_projectile", "witch_gisela_mini_projectile", _onenter, inst)
    end

    inst:DoPeriodicTask(1, Find_Witch_Gisela_Mini)

    return inst
end

return Prefab("witch_gisela", fn)
